<template>
	<view class="container">
	    <view class="form">
	      <input class="input" v-model="form.accountNumber" placeholder="请输入用户名" />
	      <input class="input" v-model="form.password" placeholder="请输入密码" type="password" />
	      <button class="button" @click="handleLogin">登录</button>
	      <view class="link" @click="goToRegister">没有账号？去注册</view>
	    </view>
		<view>
		    <button size="mini" @click="wxLogin">微信登录</button>
		</view>
	</view>

</template>

<script setup>
	import { ref } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	
	import { useUserInfoStore } from '../../store';
	import * as XLSX from 'xlsx';
	//获得store实例对象
	const userInfoStore = useUserInfoStore()
	
	// 定义响应式状态
	const form = ref({
	  accountNumber: '',
	  password: '',
	});
	
		
	async function downloadWordsBank() {
		// parseExcel(`${wx.env.USER_DATA_PATH}/${GaoKao3500}.xls`)
		
		//判断是否存在文件
		await uni.getFileSystemManager().access({
			path: `${wx.env.USER_DATA_PATH}/GaoKao3500.xls`,
			success: (res) => {
				console.log(res)
			},
			fail: (res) => {
				uni.downloadFile({
					url: 'https://mp-aa7ff953-57bf-4040-820d-fe7d9bb8d181.cdn.bspapp.com/GaoKao3500.xls',
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('文件下载成功:', res.tempFilePath);
							
							// 2. 保存文件到本地
							uni.saveFile({
								tempFilePath: res.tempFilePath, // 下载的临时文件路径
								filePath: `${wx.env.USER_DATA_PATH}/GaoKao3500.xls`, // 保存到本地的路径和文件名
								success: (saveResult) => {
									console.log('文件保存成功:', saveResult.savedFilePath);
									// parseExcel(saveResult.savedFilePath)
									parseExcel(`${wx.env.USER_DATA_PATH}/GaoKao3500.xls`)
									// resolve(saveResult.savedFilePath); // 返回保存的文件路径
									
								},
								fail: (saveError) => {
									console.error('文件保存失败:', saveError);
									reject(saveError);
								}
							});
						} else {
				            console.error('文件下载失败:', res);
				            // reject(new Error('文件下载失败'));
				        }
					}
				});
			},
		});


	}
	
	// 解析 Excel 文件
	function parseExcel(filePath) {
	    uni.getFileSystemManager().readFile({
	        filePath: filePath,
	        encoding: 'binary',
	        success: (res) => {
				const workbook = XLSX.read(res.data, { type: 'binary' });
	            // 获取第一个工作表
	            const sheetName = workbook.SheetNames[0];
	            const sheet = workbook.Sheets[sheetName];
	            // 将工作表转换为 JSON 数据
	            const jsonData = XLSX.utils.sheet_to_json(sheet, {header: 2});
				uni.setStorageSync("GaoKao3500", jsonData);
	            console.log(jsonData); // 打印解析后的数据
	        },
	        fail: (err) => {
	            console.error('文件读取失败', err);
	        }
	    });
	}
	

	// 登录逻辑
	const handleLogin = async () => {
	  if (form.value.accountNumber && form.value.password) {
		const res = await uniCloud.callFunction({
		  name: 'login',
		  data: {
			accountNumber: form.value.accountNumber,
			password: form.value.password
		  }
		})
		if (res.result.code === 200) {
		  uni.showToast({
			title: '登录成功',
			icon: 'success'
		  })
		  userInfoStore.setUserInfo(res.result.data)
		  // 登录成功后跳转到首页或其他页面
		  uni.switchTab({
			url: '/pages/tabs/progress/progress'
		  })
		} else {
		  uni.showToast({
			title: res.result.message,
			icon: 'none'
		  })
		}
		
	  } else {
	    uni.showToast({
	      title: '请输入用户名和密码',
	      icon: 'none',
	    });
	  }
	};
	
	// 跳转到注册页面
	const goToRegister = () => {
	  uni.navigateTo({
	    url: '/pages/register/register',
	  });
	};
	
	// 页面加载时执行
	onLoad(() => {
	  console.log('登录页面加载');
	  downloadWordsBank()
	});
	
    function wxLogin() {
        uni.getUserInfo({
            provider: 'weixin',
            desc: "登录的数据",
            success(user) {
                user.authResult
                uni.login({
                    provider: 'weixin',
                    onlyAuthorize: true,
                    success(lres) {
                        console.log(lres, "请求微信登录返回的数据")

                        if (lres.code) {
                            uniCloud.callFunction({
                                name: "wxLogin",
                                data: {
                                    code: lres.code
                                }
                            }).then(res => {
                                console.log("登录/注册成功 ====> ", res)
                            })
                        }
                    }
                })
            }
        })
    }
</script>

<style lang="scss" scoped>
	.container {
	  display: flex;
	  flex-direction: column;
	  justify-content: center;
	  align-items: center;
	  padding-top: 200rpx;
	  gap: 50rpx;
	  // height: 100vh;
	  .form {
	    width: 80%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		.input {
		  width: 100%;
		  height: 40px;
		  margin-bottom: 20px;
		  padding: 10px;
		  border: 1px solid #ccc;
		  border-radius: 5px;
		}
		
		.button {
		  width: 100%;
		  height: 40px;
		  background-color: #007aff;
		  color: #fff;
		  border-radius: 5px;
		  display: flex;
		  justify-content: center;
		  align-items: center;
		}
		
		.link {
		  margin-top: 10px;
		  color: #007aff;
		  text-align: center;
		  text-decoration: underline;
		}
	  }
	}




</style>